<template>
  <div class="all">
    <Card :padding="0">
      <Layout class="ivu-scroll-wrapper">
        <Header class="header">
          <img :src="currentSong.pic" width="74" height="74"/>
          <div class="header-right">
            <div class="title-bar">
              <Icon type="md-musical-note" color="#898989" size="20"/>
              <div style="margin-left: 15px">{{ currentSong.name }}</div>
            </div>
            <div class="slider-bar">
              <Slider ref="slider" v-model="currentTime" :max="duration" @on-change="sliderChange" show-tip="never"/>
            </div>
            <div class="controller-bar">
              <span>{{ "- " + reverseTime }}</span>
              <div>
                <Icon type="ios-skip-backward" color="#898989" size="15" @click.stop="prevSong"/>
                <Icon :type="playIcon" color="#898989" size="25" @click.stop="togglePlay"/>
                <Icon type="ios-skip-forward" color="#898989" size="15" @click.stop="nextSong"/>
              </div>
              <Icon style="font-weight: bolder" type="ios-list" color="#898989" size="25" @click.stop="showList = !showList"/>
            </div>
          </div>
        </Header>
        <Content v-show="showList" class="content">
          <div v-for="(item, index) in list" :key="index" class="list-item" @click.stop="currentIndex = index" :style="index === currentIndex ? 'background: #e9e9e9' : ''">
            <div class="list-num">
              <div v-if="index === currentIndex" class="list-playing"></div>
              {{ index + 1 }}
            </div>
            <div class="list-title">{{ item.name }}</div>
            <div class="list-singer">{{ item.singer }}</div>
          </div>
        </Content>
        <Footer v-show="showList" class="footer">
          <Icon type="md-musical-note" color="#898989" size="20"/>
          <div style="cursor: pointer;margin-left: 5px">
            <a style="color: #04060c" target="_blank" href="http://cyixlq.gitee.io/music/#/browse">Higher Music</a>
          </div>
          <div style="cursor: pointer;padding-right: 10px;flex: 1;text-align: right">
            <a style="color: #04060c" target="_blank" href="https://cyixlq.top/2019/01/30/iframe/">使用说明</a>
          </div>
        </Footer>
      </Layout>
    </Card>
    <audio
      ref="audio"
      :src="currentSong.url"
      @canplay="onCanPlay"
      @play="isPlay = true"
      @pause="isPlay = false"
      @ended="onEnded"
      @timeupdate="updateTime">
      您的垃圾浏览器不支持audio标签，赶紧换了吧！！！
    </audio>
  </div>
</template>

<script>
  import { getKuGouList, getNeteaseList, getTencentList } from '../api/api'
  import { createNeteaseSong, createTencentSong } from '../components/js/SongBean'
  export default {
    name: 'IFrame',
    data () {
      return {
        isPlay: false,
        reverseTime: '00:00',
        currentTime: 0,
        currentIndex: -1,
        duration: 0,
        list: [],
        showList: true,
        firstPlay: true
      }
    },
    computed: {
      currentSong () {
        if (this.currentIndex > -1) {
          return this.list[this.currentIndex]
        }
        return {
          id: 0,
          name: 'Higher Music',
          singer: '',
          pic: 'https://upload-images.jianshu.io/upload_images/8654767-49969b478ae89b47.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240',
          url: '',
          duration: 0
        }
      },
      autoPlay () {
        return this.$route.params.autoplay !== 'false'
      },
      playIcon () {
        if (this.isPlay) {
          return 'ios-pause'
        }
        return 'ios-play'
      }
    },
    watch: {
      currentSong (oldSong, newSong) {
        if (!this.autoPlay && this.firstPlay) {
          this.firstPlay = false
          return
        }
        this.firstPlay = false
        if (!newSong || oldSong.id === newSong.id) {
          return
        }
        this.$nextTick(() => {
          this.$refs.audio.play().catch(err => {
            console.log(`您的浏览器貌似不支持自动播放：${err.message}`)
          })
        })
      }
    },
    created () {
      const type = this.$route.params.type
      const id = this.$route.params.id
      switch (type) {
      case 'tencent':
        getTencentList(id).then(res => {
          const songs = []
          res[0].songlist.forEach(item => {
            songs.push(createTencentSong(item))
          })
          this.list = songs
          this.currentIndex = 0
        }).catch(err => {
          this.$Message.info(err.message)
        })
        break
      case 'netease':
        getNeteaseList(id).then(res => {
          const songs = []
          res.tracks.forEach(item => {
            songs.push(createNeteaseSong(item))
          })
          this.list = songs
          this.currentIndex = 0
        }).catch(err => {
          this.$Message.info(err.message)
        })
        break
      case 'kugou':
        getKuGouList(id).then(res => {
          this.list = res.songs
          this.currentIndex = 0
        }).catch(err => {
          this.$Message.info(err.message)
        })
        break
      default:
        break
      }
    },
    methods: {
      onEnded () {
        if (!this.nextSong()) {
          this.$refs.audio.pause()
        }
      },
      onCanPlay () {
        if (this.$route.params.type === 'tencent') {
          if (this.$refs.audio) {
            this.duration = this.$refs.audio.duration
          } else {
            this.duration = 0
          }
        } else {
          this.duration = this.currentSong.duration
        }
      },
      prevSong () {
        if (this.currentIndex > 0) {
          this.currentIndex--
        }
      },
      nextSong () {
        if (this.currentIndex < this.list.length - 1) {
          this.currentIndex++
          return true
        }
        return false
      },
      togglePlay () {
        const audio = this.$refs.audio
        const paused = audio.paused
        if (paused) {
          audio.play()
          this.isPlay = true
        } else {
          audio.pause()
          this.isPlay = false
        }
      },
      updateTime (e) {
        this.currentTime = Math.floor(e.target.currentTime)
        this.reverseTime = this.formatDate(this.duration - this.currentTime)
      },
      sliderChange (value) {
        this.currentTime = value
        this.$refs.audio.currentTime = value
      },
      formatDate (time) {
        let date = new Date(time * 1000)
        const minute = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()
        const second = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds()
        return minute + ':' + second
      }
    }
  }
</script>

<style lang="less" scoped>
  .all{
    padding: 10px;
    min-width: 250px;
    min-height: 300px;
  }
  .header {
    display: flex;
    line-height: 0px;
  }
  .header-right {
    flex: 1;
    height: 80px;
    display: flex;
    flex-direction: column;
  }
  .title-bar {
    display: flex;
    flex: 1;
    align-items: center;
  }
  .slider-bar {
    padding: 0 10px;
    align-items: center;
    flex: 1;
  }
  .controller-bar {
    display: flex;
    align-items: center;
    flex: 1;
    justify-content: space-between;
    padding: 0 5px;
  }
  .content {
    max-height: calc(~"100vh - 142px");
    overflow-y: auto;
  }
  .list-item {
    display: flex;
    height: 30px;
    padding-right: 18px;
    align-items: center;
    cursor: pointer;
  }
  .list-item:nth-child(odd) {
    background: #f7f7f7;
  }
  .list-item:hover {
    background: #eaeaea;
  }
  .list-num {
    width: 40px;
    text-align: center;
  }
  .list-playing {
    height: 22px;
    background: #df2d2d;
    width: 3px;
    float: left;
  }
  .list-title {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .list-singer {
    flex: 1;
    text-align: right;
    white-space: nowrap;
    overflow: hidden;
    padding-left: 10px;
    text-overflow: ellipsis;
  }
  .footer {
    display: flex;
    height: 40px;
    align-items: center;
  }
  ::-webkit-scrollbar {
    width: 4px; /*对垂直流动条有效*/
    height: 4px; /*对水平流动条有效*/
  }
  /*定义滑块颜色、内阴影及圆角*/
  ::-webkit-scrollbar-thumb{
    height: 7px;
    border-radius: 2px;
    background-color: #ccc;
  }
  /*定义两端按钮的样式*/
  ::-webkit-scrollbar-button {
    display: none;
  }
</style>
